package cn.xuexiluxian.open.admin.controller.common;

import cn.hutool.core.util.IdUtil;
import cn.xuexiluxian.open.admin.alioss.AliyunOssUtil;
import cn.xuexiluxian.open.admin.alioss.MultipartFileUtil;
import cn.xuexiluxian.open.common.enums.ResultStatusCodeEnum;
import cn.xuexiluxian.open.common.response.ResponseResult;
import cn.xuexiluxian.open.system.model.vo.SystemUploadVO;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 通用请求处理
 */
@Slf4j
@RestController
@RequestMapping("upload")
public class UploadController {
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    @Autowired
    private AliyunOssUtil aliyunOssUtil;

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("uploadFile")
    public ResponseResult<SystemUploadVO> uploadFile(@RequestParam("file") MultipartFile file) {
        File tempFile = null;
        try {
            String suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            tempFile = MultipartFileUtil.multipartFileToFile(file);
            String fileName = IdUtil.simpleUUID() + suffixName;
            String fileurl = aliyunOssUtil.uploadFile(tempFile, fileName);

            SystemUploadVO systemUploadVO = SystemUploadVO.builder()
                    .url(fileurl)
                    .newFileName(fileName)
                    .originalFileName(file.getOriginalFilename())
                    .suffix(suffixName)
                    .size(file.getSize())
                    .build();
            return ResponseResult.ok(systemUploadVO);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MultipartFileUtil.delteTempFile(tempFile);
        }
        return ResponseResult.error(ResultStatusCodeEnum.HTTP_ERROR);
    }

    /**
     * 通用上传请求（多个）
     */
    @PostMapping("uploadFiles")
    public ResponseResult<List<SystemUploadVO>> uploadFiles(@RequestParam("files") MultipartFile[] files){
        try {
            List<SystemUploadVO> list = new ArrayList<>();
            if(files != null && files.length > 0) {
                for(int i = 0;i < files.length;i++) {
                    MultipartFile file = files[i];
                    String suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                    File tempFile = MultipartFileUtil.multipartFileToFile(file);
                    String fileName = IdUtil.simpleUUID() + suffixName;
                    String fileurl = aliyunOssUtil.uploadFile(tempFile, fileName);
                    MultipartFileUtil.delteTempFile(tempFile);

                    SystemUploadVO systemUploadVO = SystemUploadVO.builder()
                            .url(fileurl)
                            .newFileName(fileName)
                            .originalFileName(file.getOriginalFilename())
                            .suffix(suffixName)
                            .size(file.getSize())
                            .build();
                    list.add(systemUploadVO);
                }
            }
            return ResponseResult.ok(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.error(ResultStatusCodeEnum.HTTP_ERROR);
    }

    @PostMapping("uploadFileWithWangEditor")
    public JSONObject uploadFileWithWangEditor(@RequestParam("file") MultipartFile file){
        JSONObject result = new JSONObject();
        File tempFile = null;
        try {
            String suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            tempFile = MultipartFileUtil.multipartFileToFile(file);
            String fileName = IdUtil.simpleUUID() + suffixName;
            String fileurl = aliyunOssUtil.uploadFile(tempFile, fileName);
            JSONObject data = new JSONObject();
            data.put("url", fileurl);
            data.put("alt", file.getOriginalFilename());
            data.put("href", "");
            result.put("errno", 0);
            result.put("data", data);
        } catch (Exception e) {
            result.put("errno", 1);
            result.put("message", "上传失败");
        } finally {
            MultipartFileUtil.delteTempFile(tempFile);
        }
        return result;
    }
}
